package org.duang.sms.client;

import org.duang.config.Config;
import org.duang.kit.ToolsKit;
import org.duang.sms.core.ISmsClientFactory;
import org.duang.sms.core.SmsMessage;
import org.duang.sms.utils.SmsToolsKit;

import com.taobao.api.AutoRetryTaobaoClient;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.request.AlibabaAliqinFcSmsNumSendRequest;
import com.taobao.api.response.AlibabaAliqinFcSmsNumSendResponse;

public class TaobaoSmsClient implements ISmsClientFactory<DefaultTaobaoClient>{

	private static AutoRetryTaobaoClient  client;

	private void initClient() {
		String appkey = Config.getAccessKey();
		String appsecret = Config.getAccessKeySecret();
		String smsurl = Config.getSmsUrl();
		if (appkey.isEmpty() || appsecret.isEmpty() || smsurl.isEmpty()) {
			throw new NullPointerException("get taobao sms client params is error!");
		}
		client = new AutoRetryTaobaoClient (smsurl, appkey, appsecret);
		client.setUseSimplifyJson(true);
		client.setNeedEnableLogger(false);
		client.setIgnoreSSLCheck(true);
		client.setUseGzipEncoding(false);
		client.setMaxRetryCount(3);
		client.setRetryWaitTime(100L);
	}

	@Override
	public DefaultTaobaoClient getSmsClient() {
		if (null == client) {
			initClient();
		}
		return client;
	}

	@Override
	public SmsMessage sendSms(SmsMessage message) {
		if(null == client){throw new NullPointerException("client is null");}
		AlibabaAliqinFcSmsNumSendRequest  req = new AlibabaAliqinFcSmsNumSendRequest ();
//		req.setExtend("123456");
		req.setSmsType(Config.getSmsType());
		req.setSmsFreeSignName(Config.getSignName());
		req.setSmsParam(message.getParams());
		req.setRecNum(SmsToolsKit.builderPhones(message.getPhones(), Config.getMaxRecNum()));
		req.setSmsTemplateCode(message.getTplCode());
		try {
			AlibabaAliqinFcSmsNumSendResponse  response =client.execute(req);
			if(null == response || null == response.getResult()){
				throw new NullPointerException("response is null");
			}
			message.setSuccess(response.getResult().getSuccess());
			if(message.isSuccess()) {				
				message.setContent(SmsToolsKit.builderContent(message));
			} else {
				message.setContent(response.getResult().getMsg());
			}
		} catch (Exception e) {
			e.printStackTrace();
			message.setSuccess(false);
			message.setContent(e.getMessage());
		}
		return message;
	}

	@Override
	public SmsMessage showSms(SmsMessage message) {
		if(ToolsKit.isEmpty(message)) return null;
		if(ToolsKit.isNotEmpty(message.getParams())){
			message.setContent(SmsToolsKit.builderContent(message));
		} 
		return message;
	}
}
